package me;

import java.io.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yexy
 * @date 2020/6/29 11:29 PM
 * @description
 */
public class Test {

    static final ExecutorService executorService = Executors.newCachedThreadPool();

    public static void main(String[] args) {
//        StudentSystem.run();
        removeAll("/Users/yexy/Downloads/1");
//        copyAll(new File("/Users/yexy/Downloads/Crown"),new File("/Users/yexy/Downloads/1"));
        return;
    }


    public static void removeAll(String path){
        remove(new File(path));
    }


    public static void remove(File file){
        if (file.exists()){
           if(file.isDirectory()){
               File[] files = file.listFiles();
               for (File file1 : files) {
                   remove(file1);
               }
           }
            file.delete();
        }
    }

    public static void copyAll(final File sourceFile, File destFile){

        // 在目的地创建文件夹
        final File newFile = new File(destFile,sourceFile.getName());
        // 判断拼接成的路径是否存在
        if(!newFile.exists()){
            newFile.mkdirs();
        }

        // 获取源目录中的所有的文件和文件夹
        File[] files = sourceFile.listFiles();
        for (final File file : files) {
            if(file.isFile()){

                executorService.submit(new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        copy(file,new File(newFile,file.getName()));
                        System.out.println(Thread.currentThread());
                        return null;
                    }
                });

            }else if(file.isDirectory()){
                copyAll(file, newFile);
            }
        }


    }

    public static void copy(File sourceFile,File destFile){
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;

        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream(sourceFile));
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFile));
            byte[] bytes =new byte[1024];//存储每次读取的数据
            int len = 0; //记录每次读取的有效字节个数
            while((len = bufferedInputStream.read(bytes))!=-1){
                bufferedOutputStream.write(bytes,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {

            try {
                if (bufferedOutputStream != null)
                    bufferedOutputStream.close();

                if (bufferedInputStream != null)
                    bufferedInputStream.close();
            }catch (Exception e){
                e.printStackTrace();
            }

        }

    }
}
